﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BlogEngine.Core;

namespace _4mvcBlog.Core.ModelBinders
{
    public class PostModelBinder : IModelBinder
    {

        #region IModelBinder 成员

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            HttpRequestBase request = controllerContext.HttpContext.Request;
            string id = controllerContext.RouteData.Values["id"] as string;
            Post post = bindingContext.Model as Post;
            if (!string.IsNullOrEmpty(id))
            {
                post = Post.GetPost(new Guid(id));
                if (null == post) { return null; }
                post.DateModified = DateTime.Now;
            }
            else if (null == post)
            {
                post = new Post();
            }

            post.Title = request.Form.Get("title");
            post.Content = request.Form.Get("content");
            post.Description = request.Form.Get("description");
            post.Slug = request.Form.Get("slug");
            post.IsCommentsEnabled = request.Form.IsTrue("IsCommentsEnabled");
            post.IsPublished = request.Form.IsTrue("IsPublished");

            post.Tags = new StateList<string>();
            if (!string.IsNullOrEmpty(request.Form.Get("tags")))
            {
                foreach (string tagName in request.Form.Get("tags").Split(','))
                {
                    if (tagName.Length > 0)
                        post.Tags.Add(tagName.Trim());
                }
            }

            post.Categories = new StateList<Category>();
            if (!string.IsNullOrEmpty(request.Form.Get("categories")))
            {
                string[] categories = request.Form.Get("categories").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string c in categories)
                {
                    post.Categories.Add(Category.GetCategory(new Guid(c)));
                }
            }

            return post;
        }

        #endregion
    }
}
